package scripting.map;

import client.MapleClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import scripting.item.ItemScriptManager;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

/**
 * 免责声明：本模拟器源代码下载自ragezone.com，仅用于技术研究学习，无任何商业行为。
 */
public class NodeScriptManager extends ItemScriptManager {

    private static final Logger log = LogManager.getLogger();
    private static final NodeScriptManager instance = new NodeScriptManager();

    public static final NodeScriptManager getInstance() {
        return instance;
    }

    public void getNodeScript(MapleClient c, String scriptName, int duration, int mobOid) {
        try {
            Invocable invocable = this.getInvocable("map/Nodes/" + scriptName + ".js", null);
            if (invocable == null) {
                if (c.getPlayer().isAdmin()) {
                    System.err.println("未找到 Nodes 文件中的 " + scriptName + ".js 文件");
                    c.getPlayer().dropMessage(5, "未找到 Nodes 文件中的 " + scriptName + ".js 文件.");
                }
                log.error("未找到 Nodes 文件中的 " + scriptName + ".js 文件.");
                return;
            }
            ScriptEngine scriptEngine = (ScriptEngine) invocable;
            NodeScriptMethods a2 = new NodeScriptMethods(c, scriptName);
            scriptEngine.put("nm", a2);
            invocable.invokeFunction("act", mobOid, duration);
        } catch (NoSuchMethodException | ScriptException exception) {
            System.err.println("执行Nodes文件出错  Nodes名称: " + scriptName + " 错误信息: " + exception);
            log.error("日志/脚本/Nodes脚本异常.log", "执行Nodes文件出错  Nodes名称: " + scriptName + " 错误信息: ", exception);
        }
    }
}
